package com.yeskery.nut.script.function.common;

import com.yeskery.nut.script.function.BaseMultiParamFunction;

import java.util.concurrent.ThreadLocalRandom;
import java.util.logging.Logger;

/**
 * 随机函数
 * @author sprout
 * 2022-05-17 12:27
 */
public class RandomFunction extends BaseMultiParamFunction {

    /** 日志对象 */
    private final static Logger logger = Logger.getLogger(RandomFunction.class.getName());

    /** 数组开始符号 */
    private static final String ARRAY_START_SYMBOL = "[";

    /** 数组结束符号 */
    private static final String ARRAY_END_SYMBOL = "]";

    /** 小数分隔符 */
    private static final String DOUBLE_SEPARATOR = ".";

    @Override
    public String getName() {
        return "random";
    }

    @Override
    public String apply(String content) throws Exception {
        if (content.startsWith(ARRAY_START_SYMBOL) && content.endsWith(ARRAY_END_SYMBOL)) {
            String[] splits = getParams(content.substring(1, content.length() - 2));
            return splits.length == 0 ? "" : splits.length == 1 ? splits[0] : splits[ThreadLocalRandom.current().nextInt()];
        }
        String[] splits = getParams(content);
        if (splits.length == 0) {
            return String.valueOf(ThreadLocalRandom.current().nextInt());
        }
        try {
            if (splits.length == 1) {
                if (splits[0].contains(DOUBLE_SEPARATOR)) {
                    return String.valueOf(ThreadLocalRandom.current().nextDouble(Double.parseDouble(splits[0].trim())));
                } else {
                    return String.valueOf(ThreadLocalRandom.current().nextInt(Integer.parseInt(splits[0].trim())));
                }
            } else {
                if (splits[0].contains(DOUBLE_SEPARATOR) || splits[1].contains(DOUBLE_SEPARATOR)) {
                    return String.valueOf(ThreadLocalRandom.current().nextDouble(Double.parseDouble(splits[0].trim()),
                            Double.parseDouble(splits[1].trim())));
                }
                return String.valueOf(ThreadLocalRandom.current().nextInt(Integer.parseInt(splits[0].trim()),
                        Integer.parseInt(splits[1].trim())));
            }
        } catch (NumberFormatException e) {
            logger.info("Function [" + getName() + "] Format Number Fail. At Expression: [" + content + "]");
            return content;
        }
    }
}
